<script setup lang='ts'>
import type { VxePagerEvents } from 'vxe-table'

import { useAccountCancel, useGetQueryParams, useJcEnterpriseAccountPage, useUpdateEnterpriseStatus } from '@fl/api/man-api'
import { SearchForm, SearchTable } from '@fl/components'
import { ElCard } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { useRouter } from 'vue-router'

const { push } = useRouter()

const { data: queryParamsData, isLoading: queryParamsLoading } = useGetQueryParams()

const { isPending: updateStatusIsPending, mutate: updateStatusMutate } = useUpdateEnterpriseStatus()

const { isPending: accountCancelLoading, mutate: accountCancelMutate } = useAccountCancel()

const form = ref<InstanceType <typeof SearchForm> | null>(null)

const state = ref({
    auditStatus: '',
    auditTime: [],
    certificationTime: [],
    certifiedSource: '',
    company: '',
    enterpriseSecondType: '',
    enterpriseStatus: '',
    enterpriseType: '',
})

const initialState = cloneDeep({ ...state.value })

const auditStatusList = computed(() => {
    return cloneDeep(queryParamsData.value?.auditStatusList ?? [])
})

const enterpriseStatusList = computed(() => {
    return cloneDeep(queryParamsData.value?.enterpriseStatusList ?? [])
})

const certifiedSourceList = computed(() => {
    return cloneDeep(queryParamsData.value?.certifiedSourceList ?? [])
})

const enterpriseTypeList = computed(() => {
    return cloneDeep(queryParamsData.value?.enterpriseTypeList ?? [])
})

const middleEnterpriseType = ref()

const enterpriseSecondTypeList = computed(() => {
    if (middleEnterpriseType.value) {
        const result = enterpriseTypeList.value?.filter((item: any) => item.value === middleEnterpriseType.value)
        return result?.[0]?.children ?? []
    }
    return []
})

const columns = [
    {
        label: '公司名称',
        options: [],
        prop: 'company',
        valueType: 'copy',
    },
    {
        fieldProps: {
            onChange: (val: any) => {
                middleEnterpriseType.value = val
                form.value?.formInstance.formInstance.resetFields('enterpriseSecondType')
            },
        },
        label: '企业账号类型',
        options: enterpriseTypeList,
        prop: 'enterpriseType',
        valueType: 'select',
    },
    {
        label: '企业子账号类型',
        labelWidth: '120',
        options: enterpriseSecondTypeList,
        prop: 'enterpriseSecondType',
        valueType: 'select',

    },
    {
        label: '审核状态',
        options: auditStatusList,
        prop: 'auditStatus',
        valueType: 'select',
    },
    {
        fieldProps: {
            type: 'daterange',
            valueFormat: 'YYYY-MM-DD',
        },
        label: '认证时间',
        prop: 'certificationTime',
        valueType: 'date-picker',
    },
    {
        fieldProps: {
            type: 'daterange',
            valueFormat: 'YYYY-MM-DD',
        },
        label: '审核时间',
        prop: 'auditTime',
        valueType: 'date-picker',
    },
    {
        label: '企业状态',
        options: enterpriseStatusList,
        prop: 'enterpriseStatus',
        valueType: 'select',
    },
    {
        label: '认证来源',
        options: certifiedSourceList,
        prop: 'certifiedSource',
        valueType: 'select',
    },
]

const gridOptions = reactive({
    columns: [
        { field: 'companyName', title: '公司名称' },
        { field: 'source', title: '来源' },
        { field: 'certificationTime', title: '企业认证提交时间' },
        { field: 'accountName', title: '账号名称' },
        { field: 'auditStatusName', title: '审核状态' },
        { slots: { default: 'authenticatorPhone' }, title: '认证电话' },
        { slots: { default: 'accountStatus' }, title: '企业状态' },
        { slots: { default: 'operate' }, title: '操作', width: 300 },
    ],
    rowConfig: {
        keyField: 'enterpriseId',
    },
    showOverflow: false,
})

const tablePage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

const initialPage = cloneDeep({ ...tablePage.value })

const params = computed(() => {
    return {
        objQuery: {
            ...state.value,
            auditEndTime: state.value.auditTime?.[1],
            auditStartTime: state.value.auditTime?.[0],
            certificationEndTime: state.value.certificationTime?.[1],
            certificationStartTime: state.value.certificationTime?.[0],
        },
        page: tablePage.value.currentPage,
        size: tablePage.value.pageSize,
    }
})

const { data: accountPageData, isLoading: accountPageLoading } = useJcEnterpriseAccountPage(params)

const data = computed(() => {
    return accountPageData.value?.records?.map((item) => {
        return {
            ...item,
            showPhone: false,
        }
    }) || []
})

const isLoading = computed(() => queryParamsLoading.value || accountPageLoading.value || updateStatusIsPending.value || accountCancelLoading.value)

function submit(val: any) {
    console.log(val)
    state.value = {
        ...val,
    }
    tablePage.value = cloneDeep(initialPage)
}

function reset() {
    state.value = cloneDeep(initialState)
    tablePage.value = cloneDeep(initialPage)
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

function changeAccountStatus(row: any) {
    updateStatusMutate({ enterpriseNo: row.enterpriseNo, enterpriseStatus: row.enterpriseStatus === 0 ? '1' : '0' }, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

function showLog(row: any) {
    push(`/operations-pages/operations-enterprise-management/enterprise-account-log/${row.unifiedSocialCreditCode}`)
}

function logOut(row: any) {
    accountCancelMutate(row.accountId, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

function showDetail(row: any) {
    push(`/operations-pages/operations-enterprise-management/enterprise-account/${row.enterpriseNo}`)
}

function auditPass(status: number) {
    return status === 1
}

watchEffect(() => {
    if (accountPageData.value) {
        tablePage.value.total = accountPageData.value?.total ?? 0
    }
})
</script>

<template>
    <ElCard shadow="never">
        <div class="mb-20 text-16 font-700">
            企业账号管理
        </div>

        <SearchForm ref="form"
                    v-bind="state"
                    :columns="columns"
                    submit-text="查询"
                    @submit="submit"
                    @reset="reset"
        />

        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isLoading"
                     :data="data"
                     @page-change="handlePageChange"
        >
            <template #accountStatus="{ row }">
                <!-- 0冻结 1正常 审核通过后 -->
                <vxe-switch v-if="auditPass(row.auditStatus)"
                            :model-value="row.enterpriseStatus === 1"
                            @change="changeAccountStatus(row)"
                />
            </template>

            <template #authenticatorPhone="{ row }">
                <div class="p-10">
                    {{ row.showPhone ? row.authenticatorPhoneView : row.authenticatorPhone }}
                    <div class="mt-5 cursor-pointer"
                         @click="row.showPhone = !row.showPhone"
                    >
                        {{ row.showPhone ? '隐藏' : '查看' }}
                    </div>
                </div>
            </template>

            <template #operate="{ row }">
                <div class="flex gap-10 w-full justify-center">
                    <span class="cursor-pointer"
                          @click="showDetail(row)"
                    >
                        查看
                    </span>

                    <span class="cursor-pointer"
                          @click="showLog(row)"
                    >
                        审核记录
                    </span>

                    <!-- 审核通过后显示 -->
                    <span v-if="auditPass(row.auditStatus)"
                          class="cursor-pointer"
                          @click="logOut(row)"
                    >
                        注销
                    </span>
                </div>
            </template>
        </SearchTable>
    </ElCard>
</template>
